import store from '@/stores'
import { useUserStore } from '@/stores/user'
import { getToken, removeToken } from '@/utils/local'
import type { Router } from 'vue-router'

export function beforeEach(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const { phone, getUserInfo } = useUserStore(store)
    document.title = (to.meta.title as string) || 'all-poster'
    if (getToken()) {
      // 存在 token
      if (phone) {
        if (to.path === '/login') {
          return next({ name: 'Home' })
        } else {
          next()
        }
      } else {
        // 请求用户信息
        try {
          await getUserInfo()
          next({ ...to, replace: true })
        } catch {
          removeToken()
          next({ name: 'Login' })
        }
      }
    } else {
      if (to.path === '/login') {
        next()
      } else {
        next('/login')
      }
    }
  })
}
